<template>
  <div class="app-container">
    <div class="mainbox">
      <dt-table
        ref="tableRef"
        v-loading="loading"
        :table-opts="tableOpts"
        :pagination-data="{
          total:total,
          queryParams:queryParams
        }"
        :is-column-search="false"
        @pagination="pagination"
        @handleSelectionChange="handleSelectionChange"
        @searchReset="handleReset"
        @searchChange="handleQuery"
      >
        <template #toolbarBtn>
          <el-dropdown style="margin-left: 10px">
            <el-button
              v-permission="['POSITIONMANAGE_EXPORT_BUTTON']"
              :disabled="tableOpts.tableData.length<=0"
              size="medium"
            >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown" style="width:90px;text-align:center">
              <el-dropdown-item
                @click.native="handleDownload('all')"
              >导出所有</el-dropdown-item>
              <el-dropdown-item
                @click.native="handleDownload()"
              >导出选中</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </dt-table>
    </div>
    <position-edit ref="positionRefEdit" />
  </div>
</template>

<script>
import { hasAuth } from '@/framework/utils/hasAuth'
import hrPositionApi from '@/framework/api/userCenter/hrPosition'
import positionEdit from './components/positionEdit.vue'

export default {
  name: 'PositionManage',
  dicts: ['user_status'],
  components: {
    positionEdit
  },
  data() {
    return {
      hasAuth: hasAuth('ORG_POSITION_UPDATE_STATUS'),
      tableOpts: {
        tableData: [],
        rowKey: 'positionId',
        toolbarBtn: [
          {
            label: '新增',
            permission: ['POSITIONMANAGE_ADD_BUTTON'],
            type: 'primary',
            click: (type) => {
              this.createPositionInfo(type)
            }
          }
        ],
        firstTableCol: {
          select: true,
          width: 55,
          type: 'selection'
        },
        tableCol: [
          {
            prop: 'positionName',
            label: '岗位名称',
            show: true,
            search: true
          },
          {
            prop: 'positionCode',
            label: '岗位编码',
            show: true
          },
          {
            prop: 'positionSort',
            label: '排序',
            show: true
          },
          {
            prop: 'positionRemark',
            label: '备注',
            show: true
          },
          {
            prop: 'statusFlag',
            disabled: !hasAuth,
            label: '状态',
            type: 'switch',
            search: true,
            searchslot: true,
            show: true,
            activeValue: 1,
            inactiveValue: 2,
            switchChange: (row, value) => { return this.statusChange(row) },
            formatter: () => {
              return this.dict.type.user_status
            }
          }
        ],
        operator: {
          width: 292,
          operatorBtn: [
            {
              text: '修改',
              permission: ['POSITIONMANAGE_UPDATE_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.editPositionInfo(row) }
            },
            {
              text: '删除',
              permission: ['POSITIONMANAGE_DEL_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.removePosition(row) }
            }
          ]
        }
      },
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        positionName: null
      },
      multipleSelection: [],
      loading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取页面列表
    getList() {
      this.loading = true
      hrPositionApi.fetchPage(this.queryParams).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery(formModel = {}) {
      this.queryParams = { ...this.queryParams, ...formModel }
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        positionName: null
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDetail(row) {
      this.detailOption.data = row
      this.$refs.dtDetailRef.dialogVisible = true
    },
    createPositionInfo() {
      this.$refs.positionRefEdit.openDialog('', 'create')
    },
    editPositionInfo(row) {
      this.$refs.positionRefEdit.openDialog(row, 'update')
    },
    removePosition(row) {
      this.$dtMessageBox({ title: '提示', message: `确定要删除“${row.positionName}”吗?`, type: 'warning' }).then(() => {
        hrPositionApi.delete(row).then((res) => {
          this.getList()
          this.$dtMessage({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.multipleSelection.forEach((item, index, multipleSelection) => {
            if (item.positionId === row.positionId) {
              multipleSelection.splice(index, 1)
              return multipleSelection
            } else {
              return multipleSelection
            }
          })
          if (this.multipleSelection.length == 0) {
            this.$refs.tableRef.$refs.table.clearSelection()
          }
        })
      })
    },
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        con = {
          positionIds: '',
          positionName: ''
        }
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map((res) => {
          return res.positionId
        }).join(',')
        con = {
          positionIds: ids,
          positionName: this.queryParams.positionName
        }
      }
      this.showScreenLoading()
      hrPositionApi.exportPostion(con).then((res) => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const objectUrl = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = objectUrl // 指定下载链接
        a.download = '职位信息' // 指定下载文件名
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL对象
        this.hideScreenLoading()
      }).catch((res) => {
        this.hideScreenLoading()
      })
    },
    pagination() {
      this.getList()
    },
    // 状态改变
    statusChange(row) {
      hrPositionApi.updateStatus({
        statusFlag: row.statusFlag,
        positionId: row.positionId
      }).then((res) => {
        this.getList()
        this.$dtMessage({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      }).catch(() => {
        this.getList()
      })
    }
  }
}
</script>
